package io.ouka.jvm.hotspot.selfread.domain;

import io.ouka.jvm.hotspot.selfread.util.DataTranslate;

import java.util.Arrays;

/**
 * @author ouka
 * Code
 */
public class Code {
    protected MethodInfo belongMethod;
    protected Code belongCode;

    protected int length;
    protected int index;
    protected byte[] codes;

    public Code(int length) {
        this.length = length;
        this.codes = new byte[length];
    }

    public short getUnsignedShort() {
        if (index < 0 || index >= length) {
            throw new Error("字节码指令的索引超过了最大值");
        }

        byte[] u2Arr = new byte[2];
        System.arraycopy(codes, index, u2Arr, 0, 2);

        index += 2;

        return (short) DataTranslate.byteToUnsignedShort(u2Arr);
    }

    public int getU1Code() {
        if (index < 0 || index >= length) {
            throw new Error("字节码指令的索引超过了最大值");
        }

        return Byte.toUnsignedInt(codes[index++]);
    }
    public MethodInfo getBelongMethod() {
        return belongMethod;
    }

    public void setBelongMethod(MethodInfo belongMethod) {
        this.belongMethod = belongMethod;
    }

    public Code getBelongCode() {
        return belongCode;
    }

    public void setBelongCode(Code belongCode) {
        this.belongCode = belongCode;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public byte[] getCodes() {
        return codes;
    }

    public void setCodes(byte[] codes) {
        this.codes = codes;
    }

    @Override
    public String toString() {
        return "Code{" +
                "belongMethod=" + belongMethod +
                ", belongCode=" + belongCode +
                ", length=" + length +
                ", index=" + index +
                ", codes=" + Arrays.toString(codes) +
                '}';
    }
}
